﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using KylinORM.Data.Parser.Base;

namespace KylinORM.Data.Parser
{
    /// <summary>
    /// 根据当前数据访问接口对应的数据库类型生成Sql语法解析器
    /// </summary>
    internal abstract class SqlParserProvider
    {
        /// <summary>
        /// 已注册的Sql语法解析器
        /// </summary>
        private static Dictionary<EDataProviderType, Type> registeredBuilders = new Dictionary<EDataProviderType, Type>();


        static SqlParserProvider()
        {
            RegistBuilder(EDataProviderType.SqlServer, typeof(SqlServerParser));
            RegistBuilder(EDataProviderType.MySql, typeof(MySqlParser));
            RegistBuilder(EDataProviderType.SqlServerCe, typeof(SqlServerCeParser));
        }

        /// <summary>
        /// 注册指定数据库类型的Sql语法解析器
        /// </summary>
        /// <param name="providerType"></param>
        /// <param name="sqlBuilder"></param>
        protected static void RegistBuilder(EDataProviderType providerType, Type sqlBuilder)
        {
            if (registeredBuilders.Keys.Contains(providerType))
                throw new Exception("数据库类型" + providerType + "已注册过Sql语法解析器，无法重复注册。");

            registeredBuilders.Add(providerType, sqlBuilder);
        }

        /// <summary>
        /// 为指定实体映射器创建合适的Sql语法解析器
        /// </summary>
        /// <param name="sqlParserData">解析器需要解析的数据</param>
        /// <returns></returns>
        internal static SqlParserBase GetInstance(ISqlParserData sqlParserData)
        {
            EDataProviderType providerType = DataProvider.GetInstance().ProviderType;
            if (!registeredBuilders.Keys.Contains(providerType))
                throw new Exception("数据库类型" + providerType + "尚未注册Sql语法解析器。");

            return Activator.CreateInstance(registeredBuilders[providerType], sqlParserData) as SqlParserBase;
        }

    }
}
